package hot100;

import org.junit.Test;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class RightSideView {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> rightSideView(TreeNode root) {
        //层序遍历，把每一层的末尾节点加入结果集
        Deque<TreeNode> que = new ArrayDeque<>();
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        que.addLast(root);
        int count = que.size();//每层计数，为0时到达末尾

        while (!que.isEmpty()) {
            TreeNode p = que.removeFirst();
            count--;
            if (p.left != null) que.addLast(p.left);
            if (p.right != null) que.addLast(p.right);

            if (count == 0) {
                count = que.size();
                res.add(p.val);
            }
        }

        return res;
    }

    public TreeNode constructTree(Integer[] arr, int index) {
        if (index >= arr.length || arr[index] == null) return null;
        TreeNode node = new TreeNode(arr[index]);
        node.left = constructTree(arr,2 * index + 1);
        node.right = constructTree(arr,2 * index + 2);
        return node;
    }

    @Test
    public void test() {
        TreeNode root = constructTree(new Integer[]{1, 2, 3, null, 5, null, 4}, 0);
        rightSideView(root);
    }
}
